import { useRef, useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import layout from './index.module.scss'
import uploadPhotoIcon from '@/assets/upload-photo-icon.png'
import reactSvg from '@/assets/react.svg'
import { Button, Tabs, Form, Input, Select, Switch, Flex, Modal, message, Spin } from 'antd'
import type { SelectProps } from 'antd'
import ExcelTable from '@/components/exportExcel'
import { addGroup } from '@/apis/accessManagement/group'
import { getGroupList } from '@/apis/accessManagement/group'
import { setGroup } from '@/apis/accessManagement/group'
import { getUserList } from '@/apis/accessManagement/user'
import { useLocation } from 'react-router-dom'

const GroupDetail = () => {
  const { TextArea } = Input
  const [form] = Form.useForm()
  const navigate = useNavigate()
  const location = useLocation()
  const query = new URLSearchParams(location.search)
  const state = query.get('state')
  const groupID = query.get('groupID')
  const [options, setOptions] = useState<SelectProps['options']>([])
  const [pageNumber, setPageNumber] = useState(1) // 当前页码
  const [loading, setLoading] = useState(false) // 加载状态
  const [loadingMore, setLoadingMore] = useState(false) // 加载状态
  const [hasMore, setHasMore] = useState(true) // 是否有更多数据
  const [selectedValues, setSelectedValues] = useState([])
  const [selectedAdminValues, setSelectedAdminValues] = useState([])
  const [selectedOwnerValues, setSelectedOwnerValues] = useState([])
  const [defaultGroupName, setDefaultGroupName] = useState('')
  const [defaultGroupNotice, setDefaultGroupNotice] = useState('')
  const [defaultIntroduction, setDefaultIntroduction] = useState('')
  const [defaultVerification, setDefaultVerification] = useState(1)
  const [defaultLookMember, setDefaultLookMember] = useState(1)
  const [defaultAddFriend, setDefaultAddFriend] = useState(1)

  const handleMemberChange = (value: string[]) => {
    if (value.length >= 200) {
      message.error('群成员数量不得超过200')
      return
    }
    setSelectedValues(value)
  }

  const handleAdminChange = (value: string[]) => {
    if (value.length >= 5) {
      message.error('群成员数量不得超过4')
      return
    }
    setSelectedAdminValues(value)
  }

  const handleOwnerChange = (value: string[]) => {
    setSelectedOwnerValues(value)
  }

  // 修改群组前获取群组信息
  const getGroupInfo = async () => {
    setLoading(true)
    try {
      const response = await getGroupList({
        pagination: { pageNumber: 1, showNumber: 10 },
        groupID: groupID
      })
      if (response || response.data) {
        // const { errCode, errMsg } = response;
        console.log(response)
        if (response?.errCode === 0) {
          const groupName = response.data.groups[0].groupInfo.groupName
          const groupNotice = response.data.groups[0].groupInfo.notification
          const needVerification = response.data.groups[0].groupInfo.needVerification
            ? response.data.groups[0].groupInfo.needVerification
            : 1
          const lookMember = response.data.groups[0].groupInfo.lookMemberInfo
            ? response.data.groups[0].groupInfo.lookMemberInfo
            : 0
          const addFriend = response.data.groups[0].groupInfo.applyMemberFriend
            ? response.data.groups[0].groupInfo.applyMemberFriend
            : 0
          // console.log(needVerification)
          setDefaultGroupName(groupName)
          setDefaultGroupNotice(groupNotice)
          setDefaultIntroduction(response.data.groups[0].groupInfo.introduction)
          setDefaultVerification(needVerification)
          setDefaultLookMember(lookMember)
          setDefaultAddFriend(addFriend)
        } else {
          message.error(`请求失败: ${response?.errMsg || '未知错误'}`)
        }
      } else {
        message.error('响应数据格式错误')
      }
    } catch (error) {
      console.error('Error:', error)
    } finally {
      setLoading(false)
    }
  }

  // 提交修改群组
  const subSetGroup = async () => {
    setLoading(true)
    try {
      const response = await setGroup({
        groupInfoForSet: {
          groupID: groupID,
          groupName: form.getFieldValue('groupName'),
          needVerification: defaultVerification,
          lookMemberInfo: defaultLookMember,
          applyMemberFriend: defaultAddFriend,
          notification: form.getFieldValue('notification'),
          introduction: form.getFieldValue('introduction')
        }
      })
      if (response || response.data) {
        // const { errCode, errMsg } = response;
        console.log(response)
        if (response?.errCode === 0) {
          message.success('群组修改成功')
          navigate('/group/groupManage/groupList?current=1&pageSize=10')
        } else {
          message.error(`请求失败: ${response?.errMsg || '未知错误'}`)
        }
      } else {
        message.error('响应数据格式错误')
      }
    } catch (error) {
      console.error('Error:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleSave = async () => {
    const groupName = form.getFieldValue('groupName')
    const ownerName = form.getFieldValue('ownerName')
    const adminName = form.getFieldValue('adminName')
    const usersName = form.getFieldValue('usersName')
    // const verifyMode = form.getFieldValue('verifyMode');
    if (!groupName) {
      message.error('群组名不能为空')
      return
    }
    if (state === '1' && !ownerName) {
      message.error('请选择群主')
      return
    }
    if (state === '1' && !adminName) {
      message.error('管理员不能为空')
      return
    }
    if (state === '1' && !!usersName === false) {
      message.error('群成员不能为空')
      return
    }
    // if (verifyMode === undefined) {
    //     message.error('请选择验证模式');
    //     return;
    // }
    setLoading(true)
    if (state === '1') {
      const values = await form.validateFields()
      await subAddGroup(values)
    } else {
      await subSetGroup()
    }
    // setLoading(true)
    // try {
    //     const values = await form.validateFields();
    //     await subAddGroup(values);
    // } catch (error) {
    // } finally {
    //     setLoading(false)
    // }
  }

  // 提交‘添加群组’
  const subAddGroup = async (params: any) => {
    const {
      memberUserIDs,
      adminUserIDs,
      ownerUserID,
      groupName,
      notification = '1',
      introduction = '',
      groupType = 2,
      needVerification,
      lookMemberInfo = 1,
      applyMemberFriend = 1,
      ...newParams
    } = params
    try {
      const response = await addGroup({
        ...newParams,
        groupInfo: {
          groupName,
          notification,
          introduction,
          groupType,
          needVerification: 1,
          lookMemberInfo: 1,
          applyMemberFriend: 1
        },
        memberUserIDs: selectedValues,
        adminUserIDs: selectedAdminValues,
        ownerUserID: selectedOwnerValues
      })
      if (response && response.data) {
        const { errCode, errMsg } = response
        if (errCode === 0) {
          message.success('群组添加成功')
          form.resetFields()
          navigate('/group/groupManage/groupList?current=1&pageSize=10')
        } else {
          message.error(`添加失败: ${errMsg || '未知错误'}`)
          form.resetFields()
        }
      } else {
        message.error('返回错误')
        // form.resetFields();
      }
    } catch (error) {
      console.error('Error:', error)
    } finally {
      setLoading(false)
    }
  }

  // 加载用户数据
  const fetchData = async pageNumber => {
    setLoadingMore(true)
    try {
      const data = await getUserList({
        pagination: { pageNumber, showNumber: 20 },
        keyword: '',
        normal: 1
      })
      const users = data?.data?.users
      if (!users || data.data.users.length === 0) {
        setHasMore(false) // 如果没有新数据，设置为不可加载更多
      } else {
        const formattedOptions = data.data.users.map(item => ({
          label: item.nickname,
          value: item.userID
        }))
        setOptions(prevOptions => [...prevOptions, ...formattedOptions])
      }
    } catch (error) {
      message.error('获取用户列表失败')
    } finally {
      setLoadingMore(false)
    }
  }

  // 加载下一页数据
  const loadMore = async () => {
    const nextPage = pageNumber + 1
    setPageNumber(nextPage)
  }

  useEffect(() => {
    console.log('Selected Values updated:', selectedValues)
  }, [selectedValues])

  useEffect(() => {
    if (state == '1') {
      fetchData(pageNumber)
    }
  }, [pageNumber])

  useEffect(() => {
    if (state == '2') {
      getGroupInfo()
    }
  }, [])

  useEffect(() => {
    form.setFieldsValue({ groupName: defaultGroupName })
    form.setFieldsValue({ notification: defaultGroupNotice })
    form.setFieldsValue({ introduction: defaultIntroduction })
    form.setFieldsValue({ verifyMode: defaultVerification })
    form.setFieldsValue({ addFriendMode: defaultAddFriend })
    form.setFieldsValue({ viewMode: defaultLookMember })
  }, [defaultGroupName])

  const verifyChange = (value: any) => {
    setDefaultVerification(value)
  }

  const tabsItems = [
    {
      label: '基本信息',
      key: '1',
      children: (
        <div style={{ maxWidth: '455px' }}>
          <Form.Item
            name="groupName"
            label="群组名称"
            rules={[{ required: true, message: '请输入群组名称' }]}
          >
            <Input allowClear maxLength={20} placeholder={'请输入群组名称'} defaultValue={''} />
          </Form.Item>
          {state === '1' && (
            <Form.Item
              name="ownerName"
              label="群主"
              rules={[{ required: true, message: '请选择群主' }]}
            >
              <Select
                allowClear
                style={{ width: '100%' }}
                placeholder="请选择群主"
                defaultValue={[]}
                value={selectedOwnerValues}
                onChange={handleOwnerChange}
                options={options}
                dropdownRender={menu => (
                  <>
                    {menu}
                    <div style={{ textAlign: 'center', padding: 8 }}>
                      {loading ? (
                        <Spin size="small" />
                      ) : hasMore ? (
                        <Button type="link" onClick={loadMore}>
                          加载更多
                        </Button>
                      ) : (
                        <span>没有更多数据了</span>
                      )}
                    </div>
                  </>
                )}
              />
            </Form.Item>
          )}
          {state === '1' && (
            <Form.Item
              name="adminName"
              label="管理员"
              rules={[{ required: true, message: '请选择管理员' }]}
            >
              <Select
                mode="multiple"
                allowClear
                showSearch={false}
                maxCount={5}
                style={{ width: '100%' }}
                placeholder="请选择管理员"
                defaultValue={[]}
                value={selectedAdminValues}
                onChange={handleAdminChange}
                options={options}
                dropdownRender={menu => (
                  <>
                    {menu}
                    <div style={{ textAlign: 'center', padding: 8 }}>
                      {loading ? (
                        <Spin size="small" />
                      ) : hasMore ? (
                        <Button type="link" onClick={loadMore}>
                          加载更多
                        </Button>
                      ) : (
                        <span>没有更多数据了</span>
                      )}
                    </div>
                  </>
                )}
              />
            </Form.Item>
          )}
          {state === '1' && (
            <Form.Item
              name="usersName"
              label="群成员"
              rules={[{ required: true, message: '请选择群成员' }]}
            >
              <Select
                mode="multiple"
                allowClear
                showSearch={false}
                maxCount={200}
                style={{ width: '100%' }}
                placeholder="请选择群成员"
                defaultValue={[]}
                value={selectedValues}
                onChange={handleMemberChange}
                options={options}
                dropdownRender={menu => (
                  <>
                    {menu}
                    <div style={{ textAlign: 'center', padding: 8 }}>
                      {loading ? (
                        <Spin size="small" />
                      ) : hasMore ? (
                        <Button type="link" onClick={loadMore}>
                          加载更多
                        </Button>
                      ) : (
                        <span>没有更多数据了</span>
                      )}
                    </div>
                  </>
                )}
              />
            </Form.Item>
          )}
        </div>
      )
    },
    {
      label: '群组设置',
      key: '2',
      children: (
        <div style={{ maxWidth: '455px' }}>
          <Form.Item
            name="verifyMode"
            initialValue={0}
            label="验证模式"
            rules={[{ required: true, message: '请选择验证模式' }]}
          >
            <Select
              allowClear
              onChange={verifyChange}
              placeholder="请选择验证模式"
              disabled
              options={[
                { value: 0, label: '申请需要同意，邀请直接进群' },
                { value: 1, label: '除了群主管理员邀请外，进群需要验证' },
                { value: 2, label: '直接进群' }
              ]}
            />
          </Form.Item>
          <Form.Item name="addFriendMode" label="添加好友">
            <Select
              allowClear
              placeholder=""
              disabled={true}
              options={[
                { value: 0, label: '允许群内添加好友' },
                { value: 1, label: '不允许群内添加好友' }
              ]}
            />
          </Form.Item>
          <Form.Item name="viewMode" label="查看资料">
            <Select
              placeholder=""
              disabled={true}
              options={[
                { value: 0, label: '允许查看群成员资料' },
                { value: 1, label: '不允许查看群成员资料' }
              ]}
            />
          </Form.Item>
        </div>
      )
    },
    {
      label: '群公告/简介',
      key: '3',
      children: (
        <div style={{ maxWidth: '540px' }}>
          <Form.Item name="notification" label="群公告">
            <TextArea rows={4} maxLength={200} placeholder="请输入群公告，最多不超过200字。" />
          </Form.Item>
          <Form.Item name="introduction" label="群简介">
            <TextArea rows={4} maxLength={200} placeholder="请输入群简介，最多不超过200字。" />
          </Form.Item>
        </div>
      )
    }
  ]
  return (
    <>
      <Spin spinning={loading} fullscreen size="large" />
      <div>
        {state === 1 && (
          <div className={layout.userInfo}>
            <div className={layout.userPhoto}>
              <img src={reactSvg} className={layout.photo} />
              <img src={uploadPhotoIcon} className={layout.photoIcon} />
            </div>

            <div className={layout.formView}>
              <div className={layout.formItem}>
                <div className={layout.formLabel}>群组名称:</div>
                <div className={layout.formValue}>GroupTest</div>
              </div>
              <div className={layout.formItem}>
                <div className={layout.formLabel}>群组ID:</div>
                <div className={layout.formValue}>op755975980</div>
              </div>
              <div className={layout.formItem}>
                <div className={layout.formLabel}>最近发言时间:</div>
                <div className={layout.formValue}>2012-10-16 23:55:35</div>
              </div>
            </div>
            <div className={layout.formView}>
              <div className={layout.formItem}>
                <div className={layout.formLabel}>发言状态:</div>
                <div className={layout.formValue}>正常</div>
              </div>
              <div className={layout.formItem}>
                <div className={layout.formLabel}>羽急号:</div>
                <div className={layout.formValue}>ABC_group</div>
              </div>
              <div className={layout.formItem}>
                <div className={layout.formLabel}>操作人:</div>
                <div className={layout.formValue}>admin管理员</div>
              </div>
            </div>
          </div>
        )}
        <div className={layout.formContent}>
          <Form form={form} className={layout.formView} labelAlign="right" labelCol={{ span: 6 }}>
            <Tabs defaultActiveKey="1" items={tabsItems}></Tabs>
          </Form>
        </div>
        <div className={layout.buttonView}>
          <Button type="primary" onClick={handleSave}>
            保存
          </Button>
          <Button
            style={{ marginLeft: 10 }}
            onClick={() => {
              navigate(-1)
            }}
          >
            返回
          </Button>
        </div>
      </div>
    </>
  )
}

export default GroupDetail
